<template>
  <div>
    <div class="searchbox-container">
      <div class="searchbox-container-box">
        <ul>
          <slot name="left"></slot>
          <el-tag
            v-for="(tag, index) in dynamicTags"
            :key="tag.key"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            <el-tooltip
              v-if="tag.name.length > 15"
              class="item"
              effect="dark"
              :content="tag.key + ':' + tag.name"
              placement="top-start"
            >
              <template #content>
                <span>
                  <span @click="handleTag(index, $event)"> {{ tag.key }}:</span>
                  <span @click="handleTagName(index, $event)"> {{ tag.name }}</span>
                </span>
              </template>
              <span>
                <span @click="handleTag(index, $event)"> {{ tag.key }}:</span>
                <span @click="handleTagName(index, $event)">
                  {{ tag.name.length > 15 ? tag.name.substring(0, 14) + '...' : tag.name }}</span
                >
              </span>
            </el-tooltip>
            <template v-else>
              <span @click="handleTag(index, $event)"> {{ tag.key }}:</span>
              <span @click="handleTagName(index, $event)"> {{ tag.name }}</span>
            </template>
          </el-tag>
          <el-input
            v-if="keyVisible"
            ref="saveTagKey"
            v-model="tagKey"
            class="container-input"
            style="width: 120px; margin-right: 5px"
            clearable
            @clear="clearInput"
          />
          <div class="wrapper-container">
            <el-autocomplete
              v-if="isDisabled"
              ref="saveTagInput"
              v-model="tagValue"
              class="container-input"
              style="width: 200px"
              :placeholder="placehold"
              :disabled="disabled"
              :fetch-suggestions="querySearchAsync"
              :trigger-on-focus="false"
              :select-when-unmatched="true"
              @select="changeFn"
              @keydown.down="navigateDown"
              @keydown.up="navigateUp"
              @keydown.delete="deleteNextTag"
              @click.enter="clickFn"
              @blur="blurFn"
              @focus="focusFn"
            >
              <template #default="{ item }">
                <el-tooltip
                  class="item"
                  effect="dark"
                  :disabled="!tooltipFlag"
                  :content="item.value"
                  :placement="tooltipDirection"
                >
                  <div
                    class="tooltip-wrap"
                    @mouseenter="handleTooltipIn($event)"
                    @mouseleave="handleTooltipOut($event)"
                  >
                    {{ item.value }}
                  </div>
                </el-tooltip>
              </template>
            </el-autocomplete>
            <el-autocomplete
              v-else
              ref="saveTagInput"
              v-model="tagValue"
              class="container-input"
              style="width: 200px"
              :placeholder="placehold"
              :fetch-suggestions="querySearchAsync"
              :trigger-on-focus="false"
              :select-when-unmatched="true"
              @select="changeFn"
              @keydown.down="navigateDown"
              @keydown.up="navigateUp"
              @keydown.delete="deleteNextTag"
              @click.enter="clickFn"
              @blur="blurFn"
              @focus="focusFn"
            >
              <template #default="{ item }">
                <el-tooltip
                  class="item"
                  effect="dark"
                  :disabled="!tooltipFlag"
                  :content="item.value"
                  :placement="tooltipDirection"
                >
                  <div
                    class="tooltip-wrap"
                    @mouseenter="handleTooltipIn($event)"
                    @mouseleave="handleTooltipOut($event)"
                  >
                    {{ item.value }}
                  </div>
                </el-tooltip>
              </template>
            </el-autocomplete>
            <div
              v-if="isShow"
              class="wrapper"
              @mouseenter="mouseenter()"
              @mouseleave="mouseleave()"
            >
              <div class="wrapper-dropdown">
                <ul class="dropdown">
                  <li
                    v-for="(item, index) in dataList"
                    :key="item.key"
                    :class="[currentIndex === index ? 'active' : '']"
                    @click.enter="handleClick(item, index)"
                  >
                    <span>{{ item.name }}</span>
                  </li>
                </ul>
              </div>
            </div>
            <div v-if="isDropdownShow" class="wrapper">
              <div class="wrapper-dropdown">
                <div class="wrapper-box select-item">
                  <el-checkbox
                    v-model="checkAll"
                    :indeterminate="isIndeterminate"
                    @change="handleCheckAllChange"
                    >全选</el-checkbox
                  >
                  <el-checkbox-group
                    v-model="checkedDropItems"
                    class="wrapper-checkbox"
                    @change="handleDropChange"
                  >
                    <el-checkbox
                      v-for="item in dataList[currentIndex].options"
                      :key="item.value"
                      class="wrapper-checkbox-option"
                      :label="item.value"
                      >{{ item.text }}</el-checkbox
                    >
                  </el-checkbox-group>
                </div>
                <div class="wrapper-opt">
                  <el-button
                    class="filter-item"
                    type="primary"
                    :icon="editIcon"
                    @click="handleCreateSubTag()"
                  >
                    {{ '保存' }}</el-button
                  >
                  <el-button
                    class="filter-item"
                    type="info"
                    :icon="closeIcon"
                    @click="handleCancelSubTag"
                    >{{ '取消' }}</el-button
                  >
                </div>
              </div>
            </div>
            <div
              v-if="isListShow"
              class="wrapper"
              @mouseenter="onmouseenter()"
              @mouseleave="onmouseout()"
            >
              <div class="wrapper-dropdown">
                <div class="select-item">
                  <el-row
                    v-if="dataList[currentIndex].isSearch"
                    style="padding: 10px 20px 0px 20px"
                  >
                    <el-input
                      v-model="filterText"
                      :prefix-icon="searchIcon"
                      :placeholder="$t('table.search')"
                    />
                  </el-row>
                  <ul class="dropdown">
                    <!-- v-show="item.show !== false"-->
                    <li
                      v-for="(item, index) in filteredList"
                      :key="item.key"
                      :class="[currentAzIndex === index ? 'active' : '']"
                      @click="handleSubListClick(item, index)"
                    >
                      <span>{{ item.name }}</span>
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
          <div class="container-button">
            <el-button
              v-if="dynamicTags.length > 0"
              class="filter-item"
              :icon="deleteIcon"
              @click="toDelete"
            />
            <el-button v-if="isToQuery" class="filter-item" :icon="searchIcon" @click="toQuery" />
          </div>
          <slot name="right"></slot>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { nextTick } from 'vue'
import {
  ElSpace,
  ElButton,
  ElAutocomplete,
  ElInput,
  ElTag,
  ElTooltip,
  ElCheckbox,
  ElCheckboxGroup,
  ElRow
} from 'element-plus'
import { useIcon } from '@/hooks/web/useIcon'

export default {
  components: {
    ElButton,
    ElAutocomplete,
    ElInput,
    ElTag,
    ElTooltip,
    ElCheckbox,
    ElCheckboxGroup,
    ElRow
  },
  props: {
    /* placeholder: {
      type: String,
      default() {
        return '默认按照名称搜索'
      }
    }, */
    dataList: {
      type: Array,
      default() {
        return []
      }
    },
    isDisabled: {
      type: Boolean,
      default: true
    },
    remoteData: {
      type: Array,
      default() {
        return []
      }
    },
    appendToBody: {
      type: Boolean,
      default: true
    },
    tooltipDirection: {
      type: String,
      default() {
        return 'top-start'
      }
    },
    isToQuery: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      tagKey: '',
      tagValue: '',
      inputWidth: '200px',
      currentIndex: 0,
      currentItem: null,
      currentAzIndex: 0,
      isShow: false,
      keyVisible: false,
      dynamicTags: [],
      checkAll: false,
      checkedDropItems: [],
      isIndeterminate: true,
      disabled: false,
      formVisible: false,
      title: '选择',
      treeOpt: {
        method: '',
        module: '',
        showCheckbox: true,
        label: 'name',
        validStatus: false,
        currentNodeKey: '',
        defaultExpandAll: true,
        isMultiChecked: false, // 多选opt
        apiParam: {}
      },
      tableOpt: {
        method: '', // 需要的分页接口
        module: '', // 根据后端对应的网关
        dataTable: {}, // 列表块的国际化
        searchItem: [], // 搜索块国际化
        valueString: false, // 值格式为string (一般用在弹框table为单选时候)
        hasRadio: false // 是否table弹框为单选
      },
      filterText: '',
      isLoseFocus: false,
      isSelect: false,
      isHandleClick: false,
      slotName: 'table',
      timeout: null,
      isJump: false,
      tooltipFlag: false, // 是否显示tooltip
      timer: null,
      searchIcon: null,
      deleteIcon: null,
      editIcon: null,
      closeIcon: null,
      isListShow: false,
      isDropdownShow: false
    }
  },
  computed: {
    // 根据datalist对象的type类型判断子页面是否显示,前提是tagKey为空，并且isShow为false
    subIsCheckShow(type) {
      // 为了避免参数命名冲突，外部参数名保持不变，内部使用不同变量名
      return function (checkType) {
        // 确保tagKey存在且dataList已初始化
        if (this.tagKey && this.dataList) {
          // 使用更清晰的变量名来提高代码可读性
          const isLoseFocus = this.isLoseFocus
          const isSelect = this.isSelect
          const isShow = this.isShow
          const tagKeyName = this.tagKey

          // 判断是否应该隐藏
          if (isLoseFocus && !isSelect) {
            return false
          } else {
            // 使用findIndex优化数据检索效率
            const index = this.dataList.findIndex((item) => item.name === tagKeyName)

            // 增加对边界情况的处理
            if (index === -1) {
              console.warn(`No item found with name: ${tagKeyName}`)
              return false
            }
            // 判断是否应该显示
            return isShow ? false : this.dataList[index].type === checkType
          }
        } else {
          return false
        }
      }
    },
    getDynamicTags() {
      return JSON.parse(JSON.stringify(this.dynamicTags))
    },
    placehold() {
      return '默认按照' + this.dataList[0].name + '查询'
    },
    listData() {
      return JSON.parse(JSON.stringify(this.dataList[this.currentIndex].options))
    },
    filteredList() {
      // 根据filterVal的值来过滤listData
      let filteredList = this.listData
      if (this.tagValue) {
        // 使用更高效的filter方法，并避免直接修改数据
        filteredList = this.listData.filter((item) =>
          item.name?.toLowerCase().includes(this.tagValue?.toLowerCase())
        )
      }
      if (this.filterText) {
        // 使用更高效的filter方法，并避免直接修改数据
        filteredList = this.listData.filter((item) =>
          item.name?.toLowerCase().includes(this.filterText?.toLowerCase())
        )
      }
      return filteredList
    }
  },
  watch: {
    // tagValue(val) {
    //   const { type, options } = this.dataList[this.currentIndex]
    //   if (type === 'list') {
    //     options.forEach((item) => {
    //       item.show = item.name.indexOf(val) !== -1
    //     })
    //   }
    // },
    dataList: {
      handler: function (newVal) {
        this.initData()
      },
      deep: true
    },
    getDynamicTags: {
      // 数据同源监听数据newVal和oldVal值一样,解决方法computed计算属性算一哈
      handler: function (newVal, oldVal) {
        // console.info(newVal, oldVal)
        // 都为空时不刷新，否则页面加载完毕会执行两次
        if (!(newVal.length === 0 && oldVal.length === 0)) {
          const tags = this.handleTags()
          if (!this.isJump) {
            this.$emit('select', tags)
          } else {
            this.isJump = false
          }
        }
      },
      deep: true
    }
  },
  created() {
    this.searchIcon = useIcon({ icon: 'ep:search' })
    this.deleteIcon = useIcon({ icon: 'ep:delete' })
    this.editIcon = useIcon({ icon: 'ep:edit' })
    this.closeIcon = useIcon({ icon: 'ep:close' })
    this.initData()
  },
  methods: {
    initData() {
      // 检查dataList是否存在且为数组
      if (!Array.isArray(this.dataList)) {
        console.error('dataList is not valid.')
        return
      }

      this.dynamicTags = []
      this.disabled = false // 默认情况
      this.isJump = false // 默认情况

      // 避免重复判断，提升性能
      const isSingleDropdown = this.dataList.length === 1 && this.dataList[0].type === 'dropdown'
      console.log(isSingleDropdown)
      if (isSingleDropdown) {
        this.disabled = true
      } else {
        this.dataList.forEach((item) => {
          // 数据校验
          if (!item || Object.prototype.toString.call(item) !== '[object Object]') {
            console.error('Invalid item in dataList.')
            return
          }

          const { value, type, name, id, metaDataName } = item

          if (value) {
            this.isJump = true

            if (!type) {
              this.addTagToList(name, value)
            } else {
              switch (type) {
                case 'list':
                  this.handleListType(item, name, value)
                  break
                case 'tree':
                  this.treeOpt.currentNodeKey = value
                  this.addTagToList(name, metaDataName, value)
                  break
                // 默认情况，如果type不符合预期，不处理，但可记录错误或进行其他处理
                default:
                  console.error(`Unsupported type: ${type}`)
              }
            }
          }

          if (type === 'table') {
            this.slotName = id
          }
        })
      }
    },

    // 用于减少代码重复的辅助函数
    addTagToList(key, name, originalVal = null) {
      this.dynamicTags.push({ key, name, originalVal })
    },

    // 处理list类型的逻辑，用于减少不必要的循环
    handleListType(item, name, value) {
      const index = item.options.findIndex((option) => option.key === value)
      if (index !== -1) {
        const text = item.options[index].name
        this.currentAzIndex = index
        this.addTagToList(name, text, value)
      } else {
        console.error(`Value "${value}" not found in options.`)
      }
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      // type为dropdown，关闭时清空选项
      if (this.currentItem && this.currentItem.type && this.currentItem.type === 'dropdown') {
        this.checkedDropItems = []
      }
      this.$emit('close')
    },
    handleTag(index, event) {
      this.isShow = false
    },
    handleTagName(index) {
      console.info(index)
    },
    mouseenter() {},
    mouseleave() {
      this.isShow = false
    },
    navigateDown() {
      if (!this.keyVisible) {
        this.isShow = true
        const length = this.dataList.length
        if (this.currentIndex > length - 2) {
          this.currentIndex = 0
        } else {
          this.currentIndex = this.currentIndex + 1
        }
      } else {
        if (this.dataList[this.currentIndex].type === 'list') {
          const length = this.dataList[this.currentIndex].options.length
          if (this.currentAzIndex > length - 2) {
            this.currentAzIndex = 0
          } else {
            this.currentAzIndex = this.currentAzIndex + 1
          }
        }
      }
    },
    navigateUp() {
      if (!this.keyVisible) {
        this.isShow = true
        const length = this.dataList.length
        if (this.currentIndex < 1) {
          this.currentIndex = 1
        } else {
          this.currentIndex = this.currentIndex - 1
        }
      } else {
        if (this.dataList[this.currentIndex].type === 'list') {
          const length = this.dataList[this.currentIndex].options.length
          if (this.currentAzIndex < 1) {
            this.currentAzIndex = 1
          } else {
            this.currentAzIndex = this.currentAzIndex - 1
          }
        }
      }
    },
    async initRes() {
      await nextTick()
      this.keyVisible = false
      this.tagKey = ''
      this.tagValue = ''
      this.currentIndex = 0 // fix2018 选择list或者 tree之后初始化选项
      //  this.disabled = false // 解决list 键盘事件添加之后disabled没解除限制
      // this.$refs.saveTagInput.$refs.input.focus()
    },
    async changeFn() {
      // console.log('changeFn事件触发了吗', this.tagValue, this.keyVisible, this.currentIndex)
      if (this.keyVisible) {
        const tagValue = this.tagValue
        const { type, options } = this.dataList[this.currentIndex]
        if (type === 'list') {
          // enter selected
          this.saveTags(
            this.tagKey,
            options[this.currentAzIndex].name,
            options[this.currentAzIndex].key
          )
          this.isListShow = false
          this.initRes()
        } else if (type === 'dropdown') {
          // enter selected 默认第一个
          this.saveTags(this.tagKey, options[this.currentAzIndex].text, [
            options[this.currentAzIndex].value
          ])
          this.isDropdownShow = false
          this.initRes()
        } else {
          if (tagValue) {
            this.tagKey = this.keyVisible ? this.tagKey : this.dataList[0].name
            this.saveTags(this.tagKey, this.tagValue)
            this.initRes()
          }
        }
      } else {
        this.keyVisible = true
        this.isShow = false
        this.currentItem = this.dataList[this.currentIndex]
        const { type, name } = this.currentItem
        this.tagKey = name
        if (type === 'list') {
          // fix2018 有下拉框时输入条件，如果查询不到到选项时会触发querySearchAsync 有逻辑冲突
          // 以下方式如果以后要支持动态查询，就需要改动
          await nextTick()
          this.tagValue = ''
          this.currentAzIndex = 0
          this.isListShow = true
          // this.disabled = true
        } else if (type === 'dropdown') {
          await nextTick()
          this.tagValue = ''
          this.currentAzIndex = 0
          this.isDropdownShow = true
        }
      }
    },
    clickFn() {
      if (!this.isShow) {
        this.isShow = true
      }
      // this.isShow = !this.isShow
      if (this.keyVisible) {
        this.isShow = false
      }
      if (
        this.currentItem &&
        (this.currentItem.type === 'tree' || this.currentItem.type === 'table')
      ) {
        this.formVisible = true
      }
    },
    deleteNextTag(e) {
      if (this.keyVisible) {
        if (this.tagValue === '') {
          this.currentIndex = 0
          //默认type为空的是input
          if (this.currentItem && !this.currentItem.type) {
            this.handleNextTick('', false)
          }
          if (this.currentItem && this.currentItem.type === 'list') {
            this.isListShow = false
            this.handleNextTick('', false)
          }
        }
      } else {
        if (this.tagValue === '') {
          this.currentIndex = 0
          this.dynamicTags.splice(this.dynamicTags.length - 1, 1)
        }
      }
    },
    handleClick(item, index) {
      // 先进行一些基本的状态设置，减少代码重复
      this.isHandleClick = true
      this.isShow = false
      this.currentIndex = index
      this.currentItem = item
      this.disabled = false // true
      this.filterText = ''
      if (!item || typeof item !== 'object') {
        console.error('Invalid item passed to handleClick')
        return
      }

      // 使用switch-case或策略模式优化多分支逻辑
      switch (item.type) {
        case 'tree':
          this.setupTreeOptions(item)
          this.formVisible = true
          this.title = '选择' + item.options.title
          break
        case 'table':
          this.setupTableOptions(item)
          this.formVisible = true
          this.title = '选择' + item.options.title
          break
        case 'dropdown':
          this.isDropdownShow = true
          break
        case 'list':
          this.isListShow = true
          break
        default:
          console.warn(`Unsupported item type: ${item.type}`)
      }
      // 对于所有类型，统一处理
      this.handleNextTick(item.name, true)
    },

    setupTreeOptions(item) {
      if (!item.options || typeof item.options !== 'object') {
        console.warn('Invalid item options for tree type')
        return
      }
      const {
        method,
        label = 'name',
        module = 'desk',
        validStatus,
        defaultExpandAll,
        isMultiChecked,
        apiParam = {}
      } = item.options
      this.treeOpt = {
        method,
        label,
        module,
        validStatus,
        defaultExpandAll,
        isMultiChecked,
        apiParam
      }
    },

    setupTableOptions(item) {
      if (!item.options || typeof item.options !== 'object') {
        console.warn('Invalid item options for table type')
        return
      }
      const {
        method,
        module = 'desk',
        dataTable,
        searchItem,
        valueString = false,
        hasRadio
      } = item.options
      this.tableOpt = {
        method,
        module,
        dataTable,
        searchItem,
        valueString,
        hasRadio: dataTable?.hasRadio // 更加严谨的条件判断
      }
    },
    handleCreateSubTag() {
      const data = this.dataList[this.currentIndex].options
      const nameArr = []
      data.forEach((item) => {
        const { text, value } = item
        this.checkedDropItems.forEach((item2) => {
          if (item2 === value) {
            nameArr.push(text)
          }
        })
      })
      this.saveTags(this.tagKey, nameArr.join('|'), this.checkedDropItems)
      this.handleNextTick('', false)
      this.isSelect = false
      if (this.dataList.length > 1) {
        this.disabled = false
      }
      this.isDropdownShow = false
    },
    saveTags(key, name, originalVal) {
      if (!key) {
        console.error('key is empty')
        return
      }
      const index = this.dynamicTags.findIndex((item) => {
        return item.key === key
      })
      const obj = { key: key, name: name, value: '' }
      if (originalVal) {
        obj.originalVal = originalVal
      }
      if (index > -1) {
        this.dynamicTags.splice(index, 1, obj)
      } else {
        this.dynamicTags.push(obj)
      }
    },
    async handleNextTick(key, bool) {
      await nextTick()
      this.tagKey = key
      this.tagValue = ''
      this.keyVisible = bool
      // this.$refs.saveTagInput.$refs.input.focus()
      setTimeout(() => {
        if (key) {
          this.isHandleClick = false
        }
      }, 500)
    },
    async handleCancelSubTag() {
      this.handleNextTick('', false)
      this.checkedDropItems = []
      this.isSelect = false
      this.disabled = false
      this.isDropdownShow = false
    },
    handleCheckAllChange(val) {
      this.isSelect = true
      const selectedIds = []
      if (val) {
        this.dataList[this.currentIndex].options.forEach((item) => {
          selectedIds.push(item.value)
        })
      }
      this.checkedDropItems = selectedIds
      this.isIndeterminate = false
    },
    handleDropChange(value) {
      this.isSelect = true
      const checkedCount = value.length
      const currentOptLen = this.dataList[this.currentIndex].options.length
      this.checkAll = checkedCount === currentOptLen
      this.isIndeterminate = checkedCount > 0 && checkedCount < currentOptLen
    },
    handleSubListClick(item, index) {
      this.isSelect = true
      this.currentAzIndex = index
      this.saveTags(this.tagKey, item.name, item.key)
      this.handleNextTick('', false)
      this.isSelect = false
      this.disabled = false
      this.isListShow = false
    },
    toQuery() {
      if (this.tagValue) {
        this.changeFn(this.tagValue)
      }
      const tags = this.handleTags()

      // 组件返回数组[{key: "状态" name: "上海|北京"value: "3"},{key: "云环境",name: "127.0.0.1"value: "2"}]
      this.$emit('select', tags)
    },
    handleTags() {
      const tags = JSON.parse(JSON.stringify(this.dynamicTags))
      // 根据名称填充value值，value为dynamicTags里id值
      /* 开始的 tags tree项
      * {
      *   key: "所属组织机构"
          name: "广州l"
          originalVal: "8a54060e7467733f01746774b2f50000"
          value: ""}
      * */
      /* dataList 里的tree  {
                          id: "institutionsId"
                    name: "所属组织机构"
                    options: Object
                    type: "tree"}
       */
      tags.forEach((data) => {
        this.dataList.forEach((item) => {
          if (data.key === item.name) {
            data.value = item.id
            if (data.originalVal) {
              data.metaDataName = Array.isArray(data.name) ? data.name : data.name.trim()
              data.name = data.originalVal
              delete data.originalVal
            }
          }
        })
      })
      return tags
    },
    toDelete() {
      this.dynamicTags = []
      this.currentAzIndex = 0
    },
    selectedTreeOk() {
      const treeData = this.$refs.tree.getCheckNodes()
      this.formVisible = false
      const nameKey = this.currentItem.options.label || 'name'
      this.tagValue = treeData[0][nameKey]
      this.tagKey = this.currentItem.name
      if (this.treeOpt.isMultiChecked) {
        const ids = []
        const textName = []
        treeData.forEach((item) => {
          ids.push(item.id)
          textName.push(item.name)
        })
        this.saveTags(this.tagKey, textName.join('|'), ids)
      } else {
        this.saveTags(this.tagKey, this.tagValue, treeData[0].id)
      }
      this.initRes()
      this.currentItem = null
      this.disabled = false
    },
    focusFn() {
      this.isLoseFocus = false
    },
    // input 失去焦点
    blurFn() {
      setTimeout(() => {
        if (!this.keyVisible) {
          this.isShow = false
        } else {
          if (!this.isHandleClick) {
            this.isLoseFocus = true
          }
        }
      }, 1000)
    },
    clearInput() {
      // this.placehold = '添加筛选条件'
      this.handleNextTick('', false)
      this.disabled = false
      this.isListShow = false
      this.isDropdownShow = false
    },
    querySearchAsync(queryString, cb) {
      // TODO 可扩展成后端调接口，目前数据是从remoteData传递过来的
      // 从props的remoteData中获取当前选中对象
      const currentChecked = this.remoteData.find((item) => item.name === this.tagKey)
      if (currentChecked && Object.keys(currentChecked).length > 0) {
        // 过滤查询的key对应的数据，并返回[{value:'xxx'}]格式的数据
        const restaurants = currentChecked.searchData.map((item) => {
          return { value: item[currentChecked.id] }
        })
        // remoteData: [
        // { id: 'strategyName', name: '策略名称', remoteSearch: true, searchData: [], fn: (queryString) => {
        //  return (state) => {
        //    return (state.value.toLowerCase().includes(queryString.toLowerCase()))
        //  }
        // }
        // }
        // ]
        // 支持自定义过滤方法，如上参数
        const results = queryString
          ? restaurants.filter(
              currentChecked.fn
                ? currentChecked.fn(queryString)
                : this.createStateFilter(queryString)
            )
          : restaurants
        clearTimeout(this.timeout)
        this.timeout = setTimeout(() => {
          cb(results)
        }, 500)
      } else {
        cb([])
      }
    },
    createStateFilter(queryString) {
      return (state) => {
        return state.value.toLowerCase().includes(queryString.toLowerCase())
      }
    },

    handleTooltipIn(event) {
      // scrollWidth: 对象的实际内容的宽度，不包边线宽度，会随对象中内容超过可视区后而变大。
      // offsetWidth：对象整体的实际宽度，包滚动条等边线，会随对象显示大小的变化而改变。
      this.tooltipFlag = event.target.scrollWidth > event.target.offsetWidth
    },
    handleTooltipOut(event) {
      this.tooltipFlag = false
    },
    onmouseenter() {
      clearTimeout(this.timer)
    },
    onmouseout(e) {
      if (this.isDisabled) {
        // 输入框禁用才会自动关闭下拉框
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.handleNextTick('', false)
          this.disabled = false
          this.isListShow = false
          this.isDropdownShow = false
        }, 5000)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.searchbox-container {
  width: 100%;
  margin: 0;
  position: relative;
  vertical-align: middle;
  line-height: 1;
  border: 1px solid rgb(224, 224, 230);
  border-radius: 2px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -ms-box-sizing: border-box;
  box-sizing: border-box;
  margin-bottom: 10px;
  .searchbox-container-box {
    padding: 5px;
    ul {
      margin: 0;
      padding: 0;
    }
  }
}
.cti-searchbox-tag-list {
  float: left;
  height: 22px;
  margin: 2px 0 0 2px;
  padding: 0 38px 0 10px;
  background-color: #eef0f5;
  border-radius: 2px;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -ms-box-sizing: border-box;
  box-sizing: border-box;
  position: relative;
}
.cti-searchbox-search-field {
  float: left;
  position: relative;
  margin: 2px 0 0 5px;
  white-space: nowrap;
  .cti-searchbox-prop-input {
    height: 22px;
    line-height: 22px;
    margin: 0;
    border: none;
    outline: none;
  }
}
.cti-searchbox-search-field .cti-searchbox-prop {
  display: inline-block;
  height: 22px;
  line-height: 22px;
  vertical-align: middle;
}
.wrapper {
  z-index: 999;
  position: absolute;
  margin: 10px 0 0 0;
  font-weight: 400;
  left: 10px;
}
.wrapper-dropdown {
  min-width: 200px;
  //margin: 0 auto;
  background: #fff;
  border-radius: 7px;
  border: 1px solid #e6ebf5;
  box-shadow: 0 1px 1px rgba(50, 50, 50, 0.1);
  cursor: pointer;
  outline: none;
  font-weight: bold;
  color: #8aa8bd;
}
.wrapper-opt {
  padding-bottom: 7px;
  position: sticky;
  bottom: 1px;
  display: flex;
  justify-content: center;
}
.wrapper-dropdown .dropdown {
  padding: 6px 0 !important;
  li {
    font-size: 14px;
    padding: 0 20px;
    position: relative;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #606266;
    font-weight: normal;
    height: 34px;
    line-height: 34px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    cursor: pointer;
    &.active,
    &:hover {
      background-color: #f5f7fa;
    }
  }
}
.wrapper-dropdown .dropdown li:hover span {
  background: #f3f8f8;
}

.wrapper-dropdown .dropdown li:first-of-type span {
  border-radius: 7px 7px 0 0;
}
.wrapper-dropdown .dropdown:after {
  content: '';
  width: 0;
  height: 0;
  position: absolute;
  bottom: 100%;
  left: 35px;
  border-width: 0px 6px 6px 6px;
  border-style: solid;
  border-color: #e6ebf5 transparent;
}
.wrapper-container {
  display: inline-block;
  position: relative;
}
.wrapper-box {
  padding: 10px;
}
.wrapper-checkbox {
  border-bottom: 1px solid #cdcdcd;
  // margin-bottom: 10px;
}
.wrapper-checkbox-option {
  color: #606266;
  font-weight: 500;
  font-size: 14px;
  position: relative;
  cursor: pointer;
  display: block;
  white-space: nowrap;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  // margin: 0 0 5px;
}
.container-input {
  margin-left: 10px;
}
.container-button {
  display: inline;
  float: right;
}

.el-tag {
  margin-right: 5px;
}
.select-item {
  // max-height: $contentMinHeight;
  max-height: 285px;
  overflow-x: hidden;
  overflow-y: auto;
}
.tooltip-wrap {
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
